package cn.fufeiii.bt.common.aspect.validation;

import cn.fufeiii.bt.common.code.CommonResultEnum;
import cn.fufeiii.bt.common.util.ValidationUtil;
import cn.fufeiii.bt.common.util.result.CommonResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 校验切面
 *
 * @author FuFei
 */
@Order(15)
@Aspect
@Component
public class ModelValidationAspect {

    /**
     * 切类上的注解
     */
    @Pointcut("@within(cn.fufeiii.bt.common.aspect.validation.ModelValidation)")
    public void pointcut1() {
    }

    /**
     * 切方法上的注解
     */
    @Pointcut("@annotation(cn.fufeiii.bt.common.aspect.validation.ModelValidation)")
    public void pointcut2() {
    }

    /**
     * 切面
     */
    @Around("pointcut1() || pointcut2()")
    public Object advice(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if (args != null) {
            for (Object arg : args) {
                ValidationUtil.Result result = ValidationUtil.validate(arg);
                if (!result.isOk()) {
                    return CommonResult.fail(CommonResultEnum.REQUEST_ABNORMALITY.getCode(), result.getInfo());
                }
            }
        }
        return joinPoint.proceed();
    }
}
